<template>
  <form-item-wrapper :designer="designer" :field="field" :rules="rules" :design-state="designState"
    :parent-widget="parentWidget" :parent-list="parentList" :index-of-parent-list="indexOfParentList"
    :sub-form-row-index="subFormRowIndex" :sub-form-col-index="subFormColIndex" :sub-form-row-id="subFormRowId"
    @mousedown="handleNumberFocus">
    <el-input-number ref="fieldEditor" v-model="fieldModel" v-show="!isReadMode && isEdit" class="full-width-input"
      :disabled="field.options.readonly || field.options.disabled || field.options?.isAllowEditSelectorField == '2'" :controls="showControls" :controls-position="field.options.controlsPosition"
      :placeholder="field.options.placeholder" :min="Number(field.options.min)" :max="Number(field.options.max)"
      :precision="field.options.precision" :step="field.options.step" 
      :value-on-clear="0"
      @focus="handleFocusCustomEvent"
      @blur="handleBlurCustomEvent(); field.options.numDisplayFormat != 'number' ? isEdit = false : ''"
      @change="onFieldChangeEvent" @input="handleNumberInputEvent" @keydown="handleKeyDown" @compositionstart="handleCompositionStart" @compositionend="handleCompositionEnd">
    </el-input-number>
    <el-input class="full-width-input" v-model="notNumber"
      v-show="!isReadMode && field.options.numDisplayFormat != 'number' && !isEdit" :disabled="field.options.readonly || field.options.disabled"
      :placeholder="field.options.placeholder" :min="Number(field.options.min)" :max="Number(field.options.max)"
      :precision="field.options.precision" :step="field.options.step" @focus="isEdit = true" @blur="isEdit = true" />
    <template v-if="isReadMode">
      <span class="readonly-mode-field">
        <template v-if="field.options.numDisplayFormat == 'percent'">
          {{  notNumber }}
        </template>
        <template v-else-if="field.options.numDisplayFormat == 'subcontractor'">
          {{  notNumber }}
        </template>
        <template v-else>
          {{ contentForReadMode }}
        </template>
      </span>
    </template>
  </form-item-wrapper>
</template>

<script>
import FormItemWrapper from './form-item-wrapper'
import emitter from '@/utils/emitter'
import i18n, { translate } from "@/utils/i18n";
import fieldMixin from "@/components/form-designer/form-widget/field-widget/fieldMixin";

export default {
  name: "number-widget",
  componentName: 'FieldWidget',  //必须固定为FieldWidget，用于接收父级组件的broadcast事件
  mixins: [emitter, fieldMixin, i18n],
  props: {
    field: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,

    designState: {
      type: Boolean,
      default: false
    },

    subFormRowIndex: { /* 子表单组件行索引，从0开始计数 */
      type: Number,
      default: -1
    },
    subFormColIndex: { /* 子表单组件列索引，从0开始计数 */
      type: Number,
      default: -1
    },
    subFormRowId: { /* 子表单组件行Id，唯一id且不可变 */
      type: String,
      default: ''
    },

  },
  components: {
    FormItemWrapper,
  },
  data() {
    return {
      oldFieldValue: null, //field组件change之前的值
      fieldModel: null,
      fieldModelBack: null,
      rules: [],
      isEdit: true,
    }
  },
  computed: {
    showControls() {
      return this.field.options.controls === undefined ? true : this.field.options.controls
    },

    contentForReadMode() {
      return (this.fieldModel === null || this.fieldModel === undefined) ? '' : Number(this.fieldModel).toFixed(this.field.options.precision)
    },

    notNumber() {
      let { numDisplayFormat: type } = this.field.options

      const num = Number(this.fieldModel)
      let percentNum = num.toLocaleString('zh', {style:'percent', minimumFractionDigits: this.field.options.percentPrecision, maximumFractionDigits: this.field.options.percentPrecision}) 
      let subcontractor = num.toLocaleString('zh', {minimumFractionDigits: this.field.options.precision, maximumFractionDigits: this.field.options.precision})
      if (type != 'number') {
        return (this.fieldModel === null || this.fieldModel === undefined) ? '' : type == 'percent' ? percentNum : subcontractor
      }
    },
  },
  watch: {
    'field.options.defaultValue': {
      handler() {
        // this.field.options.defaultValue = Number(this.field.options.defaultValue)
        this.initFieldModel()
      },
      deep: true,
      immediate: true,
    },
    'field.options.numDisplayFormat': function () {
      this.isEdit = this.field.options.numDisplayFormat == 'number'
    },
  },
  beforeCreate() {
    /* 这里不能访问方法和属性！！ */
  },

  created() {
    /* 注意：子组件mounted在父组件created之后、父组件mounted之前触发，故子组件mounted需要用到的prop
       需要在父组件created中初始化！！ */
    this.isEdit = this.field.options.numDisplayFormat == 'number'
    this.registerToRefList()
    this.initFieldModel()
    this.initEventHandler()
    this.buildFieldRules()

    this.handleOnCreated()
  },

  mounted() {
    this.handleOnMounted()
  },

  beforeUnmount() {
    this.unregisterFromRefList()
  },

  methods: {
    handleNumberFocus() {
      setTimeout(() => {
        this.$refs.fieldEditor.focus()
      }, 0);
    },
    /**
     * 键盘事件处理函数，禁止输入e和E字符
     * @param e 键盘事件对象
     */
    handleKeyDown(e) {
      let key = e.key
      if (key === 'e' || key === 'E') {
        e.returnValue = false
        return false
      }
      return true
    },
    // 处理中文模式输入框的composition事件处理函数，防止中文输入法输入时，失去焦点后无法恢复原有值的问题
    handleCompositionStart(e) {
      this.fieldModelBack = e.target.value
    },
    handleCompositionEnd(e) {
      e.target.value = this.fieldModelBack
      this.fieldModel = this.fieldModelBack
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../../../../styles/global.scss";
/* form-item-wrapper已引入，还需要重复引入吗？ */

.full-width-input {
  width: 100% !important;
}

::v-deep .full-width-input .el-input__inner {
  text-align: center;
}
</style>
